package com.zjsm.gobang;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RadialGradientPaint;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Ellipse2D;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import com.zjsm.music.Begin;
import com.zjsm.music.Chessman;
import com.zjsm.music.Fail;
import com.zjsm.music.Mention;
import com.zjsm.music.Win;
import com.zjsm.system.HelpIn;
import com.zjsm.system.Intro;

public class GoBang_PP extends JFrame implements IChess {

	private static final long serialVersionUID = 1L;
	private JPanel jPanel;
	private Image image;
	private int i = 0;
	private int count = 0;
	private byte[][] chess = new byte[21][21];
	private boolean ischessed = false;
	private boolean isyouturn = false;
	private boolean isBlack;
	private byte color = 0;
	private byte[] lastchess = new byte[2];
	private byte[] thelast = new byte[2];
	private ServerSocket ss;
//	protected final ImagePanel background = new ImagePanel("resource/img/background1.jpg");

	public GoBang_PP() {
		this.setTitle("这就是命五子棋");
		this.setSize(widthSize, heightSize);
		int x = Toolkit.getDefaultToolkit().getScreenSize().width;
		int y = Toolkit.getDefaultToolkit().getScreenSize().height;

		this.setLocation((x - widthSize) / 2, (y - heightSize) / 2);
		this.setResizable(false);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JMenuBar bar = new JMenuBar();
		JMenu game = new JMenu("游戏");
		JMenu help = new JMenu("帮助");

		JMenuItem jianli = new JMenuItem("创建房间");
		JMenuItem lianjie = new JMenuItem("进入房间");
		JMenuItem chongqi = new JMenuItem("重新开始");
		JMenuItem tuichu = new JMenuItem("退出游戏");
		JMenuItem guanyu = new JMenuItem("关于游戏");
		JMenuItem bangzhu = new JMenuItem("游戏帮助");


		tuichu.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {

				int i = JOptionPane.showConfirmDialog(GoBang_PP.this, "您确定要退出游戏吗？", "系统提示", JOptionPane.YES_NO_OPTION);
				if (i == 0) {
					System.exit(0);
				}
			}
		});

		guanyu.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
//				JOptionPane.showMessageDialog(GoBang_PP.this, "易趣五子棋--xupt这就是命小组", "关于游戏",JOptionPane.INFORMATION_MESSAGE);
				Intro help = new Intro();
				help.setVisible(true);
			}
		});

		jianli.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				new server().start();
				isBlack = true;
			}
		});

		lianjie.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				new client().start();
				isBlack = false;
			}
		});
		
		
		chongqi.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				int i = JOptionPane.showConfirmDialog(GoBang_PP.this, "您确定要重新开始吗？", "系统提示", JOptionPane.YES_NO_OPTION);
				if (i == 0) {
					if (ss != null) {
						try {
							ss.close();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
					GoBang_PP gPp = null;
					new GoBang_PP();
					GoBang_PP.this.dispose();
				}
			}
		});
		
		bangzhu.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				HelpIn help = new HelpIn();
				help.setVisible(true);
			}
		});
		
		game.add(jianli);
		game.add(lianjie);
		game.add(chongqi);
		game.add(tuichu);

		help.add(bangzhu);
		help.add(guanyu);

		bar.add(game);
		bar.add(help);
		
		jPanel = new JPanel();
		jPanel.setBackground(new Color(238, 173, 14));
		this.add(jPanel);
		
//		background.setBounds(0, 0, x, y);
//		background.setLayout(null);
//		this.add(background);

		this.setJMenuBar(bar);
		try {
//			image = ImageIO.read(new File("../resource/img/background1.jpg"));
		} catch (Exception e) {
			// TODO: handle exception
		}
		JFrameMouseeListenter jml = new JFrameMouseeListenter();
		this.addMouseListener(jml);
		this.setVisible(true);

	}

	public void paint(Graphics g) {

		super.paint(g);
		Graphics2D gr = (Graphics2D) jPanel.getGraphics();
//		Graphics gr = jPanel.getGraphics();
//		gr.drawImage(image, 0, 0, 700, 750, null);
		for (int i = 0; i < 21; i++) {
			gr.drawString(i + "", Size, 55 + Size * i);
			gr.drawLine(X, Y+i*Size, X+Size*(Col-1), Y+i*Size);
		}
		for (int i = 0; i < 21; i++) {
			gr.drawString((char) (i + 'A') + "", 45 + i * 30, 35);
			gr.drawLine(X+i*Size, Y, X+i*Size, Y+Size*(Row-1));
		}
		gr.fillOval(496, 196, 7, 7);
		gr.fillOval(496, 496, 7, 7);
		gr.fillOval(196, 496, 7, 7);
		gr.fillOval(196, 196, 7, 7);
		gr.fillOval(346, 346, 7, 7);

//		gr.fillOval(48, 646, 7, 7);
//		gr.fillOval(646, 646, 7, 7);
//		gr.fillOval(646, 48, 7, 7);
//		gr.fillOval(48, 48, 7, 7);

		for (int i = 0; i < chess.length; i++) {
			for (int j = 0; j < chess[i].length; j++) {
				int x = X + i*Size - Size/2 + 1;
				int y = Y + j*Size - Size/2 + 39;
				if (chess[i][j] == 1) {
//					gr.setColor(Color.black);
//					gr.fillOval(i * 30 + 38, j * 30 + 38, 25, 25);
					RadialGradientPaint paint = new RadialGradientPaint(x - Size/2 + 37,
							y - Size/2 - 20, 20 , new float[]{0f, 1f}, new Color[]{Color.WHITE, Color.BLACK});
					gr.setPaint(paint);
					gr.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
					gr.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT);
					Ellipse2D e = new Ellipse2D.Float(x-Size/2 + 17 , y-Size/2 - 22, 25, 25);
					gr.fill(e);
					
					if(i == thelast[0] && j == thelast[1]) {
						gr.setColor(Color.RED);
						gr.drawRect(x-Size/2 + 17, y-Size/2 - 22, 25, 25);
					} else if(i == lastchess[0] && j == lastchess[1]) {
						gr.setColor(Color.BLUE);
						gr.drawRect(x-Size/2 + 17, y-Size/2 - 22, 25, 25);
					}
				}

				else if (chess[i][j] == -1) {
					RadialGradientPaint paint = new RadialGradientPaint(x - Size/2 + 37,
							y - Size/2 - 20, 70 , new float[]{0f, 1f}, new Color[]{Color.WHITE, Color.BLACK});
					gr.setPaint(paint);
					gr.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
					gr.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT);
					Ellipse2D e = new Ellipse2D.Float(x-Size/2 + 17 , y-Size/2 - 22, 25, 25);
					gr.fill(e);
					
					if(i == thelast[0] && j == thelast[1]) {
						gr.setColor(Color.RED);
						gr.drawRect(x-Size/2 + 17, y-Size/2 - 22, 25, 25);
					} else if(i == lastchess[0] && j == lastchess[1]) {
						gr.setColor(Color.BLUE);
						gr.drawRect(x-Size/2 + 17, y-Size/2 - 22, 25, 25);
					}
				}
				
			}
		}
		
	}

	public boolean isover(int x, int y) {
		int samecolor = 0;

		for (int i = x - 4; i <= x + 4; i++) {
			if (i >= 0 && i <= 20) {
				if (chess[i][y] == chess[x][y]) {
					samecolor++;

					if (samecolor == 5) {
						return true;
					}
				} else {
					samecolor = 0;
				}
			}
		}

		for (int i = y - 4; i <= y + 4; i++) {
			if (i >= 0 && i <= 20) {
				if (chess[x][i] == chess[x][y]) {
					samecolor++;
					if (samecolor == 5) {
						return true;
					}
				} else {
					samecolor = 0;
				}
			}
		}
		for (int i = x - 4, j = y + 4; i <= x + 4 && j >= y - 4; i++, j--) {
			if (i >= 0 && i < +20 && j >= 0 && j <= 20) {
				if (chess[i][j] == chess[x][y]) {
					samecolor++;
					if (samecolor == 5) {
						return true;
					}
				} else {
					samecolor = 0;
				}
			}
		}
		for (int i = x - 4, j = y - 4; i <= x + 4 && j <= y + 4; i++, j++) {
			if (i >= 0 && i < +20 && j >= 0 && j <= 20) {
				if (chess[i][j] == chess[x][y]) {
					samecolor++;
					if (samecolor == 5) {
						return true;
					}
				} else {
					samecolor = 0;
				}
			}
		}

		return false;

	}

	public static void main(String[] args) {

		new GoBang_PP();
	}

	class JFrameMouseeListenter implements MouseListener {

		@Override
		public void mouseClicked(MouseEvent e) {
			// TODO Auto-generated method stub

			// System.out.println(e.getX()+":"+e.getY());
			/*
			 * Graphics gr = jPanel.getGraphics(); i++; if(i%2==0){ gr.fillOval(e.getX()-18,
			 * e.getY()-36, 25, 25);
			 * 
			 * } else { gr.drawOval(e.getX()-18, e.getY()-36, 25, 25); }
			 */

			// System.out.println(e.getX()+" "+e.getY());

			if (isyouturn && !ischessed) {
				//落子音效
				try {
					new Chessman().play();
				} catch (IOException ee) {
					// TODO 自动生成的 catch 块
					ee.printStackTrace();
				}
				
				int x = e.getX();
				int y = e.getY();
//				System.out.println(x + " " + y);
				if (x < 47 || x > 653 || y < 97 | y > 703) {
					return;
				} else {
					x = (int) Math.round((x - 50) / 30.0);
					y = (int) Math.round((y - 100) / 30.0);
					if (chess[x][y] == 0) {
						count++;
						if (count % 2 == 1) {
							chess[x][y] = 1;
						} else {
							chess[x][y] = -1;
						}
						chess[x][y] = color;
						ischessed = true;
						lastchess[0] = (byte) x;
						lastchess[1] = (byte) y;
						GoBang_PP.this.repaint();
						if (GoBang_PP.this.isover(x, y)) {
							if(chess[x][y] == 1) {
								//胜利音效
								try {
									new Win().play();
								} catch (IOException ee) {
									// TODO 自动生成的 catch 块
									ee.printStackTrace();
								}
							} else if(chess[x][y] == -1 && !isBlack) {
								//胜利音效
								try {
									new Win().play();
								} catch (IOException ee) {
									// TODO 自动生成的 catch 块
									ee.printStackTrace();
								}
							}
							JOptionPane.showMessageDialog(GoBang_PP.this, (chess[x][y] == 1) ? "黑棋获胜" : "白棋获胜", "系统提示",JOptionPane.INFORMATION_MESSAGE);
						}
					}
				}
			}

		}

		@Override
		public void mouseEntered(MouseEvent e) {
			// TODO Auto-generated method stub
			// System.out.println("mouseEntered");
		}

		@Override
		public void mouseExited(MouseEvent e) {
			// TODO Auto-generated method stub
			// System.out.println("mouseExited");
		}

		@Override
		public void mousePressed(MouseEvent e) {
			// TODO Auto-generated method stub

		}

		@Override
		public void mouseReleased(MouseEvent e) {
			// TODO Auto-generated method stub

		}

	}

	class server extends Thread {
		public void run() {
			try {
				ss = new ServerSocket(10000);
				InetAddress iaAddress = null;
				iaAddress = iaAddress.getLocalHost();

				JOptionPane.showMessageDialog(GoBang_PP.this, "房间创建成功，等待玩家进入，地址：" + iaAddress.getHostAddress() ,"系统提示", JOptionPane.INFORMATION_MESSAGE);
				Socket socket = ss.accept();
				String address = socket.getInetAddress().getHostAddress();

				int option = JOptionPane.showConfirmDialog(GoBang_PP.this, address + "已经进入房间，等待游戏开始","系统提示", JOptionPane.YES_OPTION);
				if(option == JOptionPane.YES_OPTION) {
					//开始音效
					try {
						new Begin().play();
					} catch (IOException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
				}
				
				isyouturn = true;
				ischessed = false;
				color = 1;

				InputStream is = socket.getInputStream();
				OutputStream os = socket.getOutputStream();

				while (true) {
					while (isyouturn && !ischessed) {
						try {
							Thread.sleep(100);
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
					os.write(lastchess);
					os.flush();
					isyouturn = false;
					byte[] b = new byte[2];
					is.read(b);
					byte x = b[0];
					byte y = b[1];

					GoBang_PP.this.chess[x][y] = -1;
					thelast[0] = x;
					thelast[1] = y;
					GoBang_PP.this.repaint();
					if (GoBang_PP.this.isover(x, y)) {
						if(chess[x][y] == 1) {
							//胜利音效
							try {
								new Win().play();
							} catch (IOException e) {
								// TODO 自动生成的 catch 块
								e.printStackTrace();
							}
						} else if(chess[x][y] == -1) {
							//失败音效
							try {
								new Fail().play();
							} catch (IOException e) {
								// TODO 自动生成的 catch 块
								e.printStackTrace();
							}
						} 
						JOptionPane.showMessageDialog(GoBang_PP.this, (chess[x][y] == 1) ? "黑棋获胜" : "白棋获胜", "系统提示",JOptionPane.INFORMATION_MESSAGE);
						isyouturn = false;
						break;
					}
					isyouturn = true;
					ischessed = false;
				}
			} catch (BindException e) {
				// TODO: handle exception
				//提示音效
				try {
					new Mention().play();
				} catch (IOException ex) {
					// TODO 自动生成的 catch 块
					ex.printStackTrace();
				}
				JOptionPane.showMessageDialog(GoBang_PP.this, "端口被占用，房间创建失败","系统提示",JOptionPane.INFORMATION_MESSAGE);
			} catch (IOException e1) {
				// 提示音效
				try {
					new Mention().play();
				} catch (IOException ex) {
					// TODO 自动生成的 catch 块
					ex.printStackTrace();
				}
				JOptionPane.showMessageDialog(GoBang_PP.this, "连接已断开","系统提示",JOptionPane.INFORMATION_MESSAGE);
//				e1.printStackTrace();
			}
		}
	}

	class client extends Thread {
		public void run() {
			String address = JOptionPane.showInputDialog("请输入房间IP地址");
			try {
				Socket socket = new Socket(address, 10000);

				int option = JOptionPane.showConfirmDialog(GoBang_PP.this, "已经进入房间，等待游戏开始","系统提示",JOptionPane.YES_OPTION);
				if(option == JOptionPane.YES_OPTION) {
					//开始音效
					try {
						new Begin().play();
					} catch (IOException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
					JOptionPane.showMessageDialog(GoBang_PP.this, "等待对方落子","系统提示",JOptionPane.INFORMATION_MESSAGE);
				}
				
				isyouturn = false;
				ischessed = false;
				color = -1;

				InputStream is = socket.getInputStream();
				OutputStream os = socket.getOutputStream();

				while (true) {
					byte[] b = new byte[2];
					is.read(b);
					byte x = b[0];
					byte y = b[1];
					GoBang_PP.this.chess[x][y] = 1;
					thelast[0] = x;
					thelast[1] = y;
					GoBang_PP.this.repaint();
					if (GoBang_PP.this.isover(x, y)) {
						if(chess[x][y] == -1) {
							//胜利音效
							try {
								new Win().play();
							} catch (IOException e) {
								// TODO 自动生成的 catch 块
								e.printStackTrace();
							}
						} else if(chess[x][y] == 1) {
							//失败音效
							try {
								new Fail().play();
							} catch (IOException e) {
								// TODO 自动生成的 catch 块
								e.printStackTrace();
							}
						} 
						JOptionPane.showMessageDialog(GoBang_PP.this, (chess[x][y] == 1) ? "黑棋获胜" : "白棋获胜", "系统提示",JOptionPane.INFORMATION_MESSAGE);
						isyouturn = false;
						break;
					} 
					isyouturn = true;
					ischessed = false;
					while (isyouturn && !ischessed) {
						try {
							Thread.sleep(100);
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
					os.write(lastchess);
//					System.out.println("发送" + lastchess[0] + ":" + lastchess[1]);
					os.flush();

					isyouturn = false;
				}

			} catch (Exception e) {
				// 提示音效
				try {
					new Mention().play();
				} catch (IOException ex) {
					// TODO 自动生成的 catch 块
					ex.printStackTrace();
				}
				JOptionPane.showMessageDialog(GoBang_PP.this, "连接已断开","系统提示",JOptionPane.INFORMATION_MESSAGE);
			}

		}
	}
}
